<template>
  <el-main>
    <!-- 搜索栏 -->
    <el-form :model="listParam" ref="searchRef" label-width="80px" :inline="true" size="small">
      <el-form-item>
        <el-input placeholder="请输入角色的名称" v-model="listParam.roleName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="searchBtn" icon="el-icon-search">搜索</el-button>
        <el-button @click="resetBtn" icon="el-icon-close" type="danger" plain>重置</el-button>
        <el-button icon="el-icon-plus" type="success" @click="addBtn">新增角色</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table :data="tableData" :height="listParam.tableHeight" border stripe>
      <el-table-column prop="roleName" label="角色名称"></el-table-column>
      <el-table-column prop="remark" label="角色备注"></el-table-column>
      <el-table-column label="操作" align="center" width="300">
        <template slot-scope="scope">
          <el-button type="primary" size="small" icon="el-icon-edit" plain @click="editBtn(scope.row)">编辑</el-button>
          <el-button type="primary" size="small" icon="el-icon-edit" plain @click="assignBtn(scope.row)">分配权限
          </el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" plain @click="deleteBtn(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChange"
      @current-change="currentChange"
      :current-page.sync="listParam.currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="listParam.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="listParam.total" background>
    </el-pagination>
    <sys-dialog
      :title="dialog.title"
      :visible="dialog.visible"
      :width="dialog.width"
      :height="dialog.height"
      @onClose="onClose"
      @onConfirm="onConfirm"
    >
      <div slot="content">
        <el-form :model="addModel" ref="addRef" :rules="rules" label-width="80px" size="small">
          <el-row>
            <el-col :span="12" :offset="0">
              <el-form-item prop="roleName" label="角色名称">
                <el-input v-model="addModel.roleName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="角色备注">
                <el-input v-model="addModel.remark"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12" :offset="0">
              <el-form-item prop="roleType" label="角色类型">
                <el-select v-model="addModel.roleType" placeholder="请选择角色类型">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </sys-dialog>
    <!--    分配权限-->
    <sys-dialog :title="assignDialog.title" :width="assignDialog.width"
                :heighta="assignDialog.height" :visible="assignDialog.visible"
                @onClose="assignClose" @onConfirm="assignConfirm"
    >
      <div slot="content">
        <el-tree
          ref="assignTree"
          show-checkbox
          :data="assignTreeData"
          node-key="menuId"
          :props="defaultProps"
          default-expand-all
          :default-checked-keys="assignTreeChecked"
        >
        </el-tree>
      </div>
    </sys-dialog>
  </el-main>

</template>

<script>
//这是弹窗组件
import SysDialog from '@/components/dialog/StstemDialog.vue'
import {getListApi, addRoleApi, editRoleApi, deleteRoleApi, getAssignRoleApi,saveAssignRoleApi} from '@/api/role'

import {getUserId} from "@/utils/auth";

export default {
  //注册弹框组件
  components: {
    SysDialog,
  },
  data() {
    return {
      defaultProps: {children: "children", label: "title"},
      //树数据
      assignTreeData: [],
      //角色原来的权限
      assignTreeChecked: [],
      //角色id
      roleId: '',
      //分配弹框权限的属性
      assignDialog: {
        title: '',
        width: 300,
        height: 400,
        visible: false
      },
      //角色类型
      options: [{
        value: '1',
        label: '系统用户'
      }, {
        value: '2',
        label: '学生'
      },],
      rules: {
        roleName: [{trigger: 'blur', required: true, message: '请填写角色名称'}],
        roleType: [{trigger: 'blur', required: true, message: '请选择角色类型'}]
      },
      addModel: {
        type: '',
        roleId: '',
        roleName: '',
        roleType: '',
        remark: ''
      },
      listParam: {
        tableHeight: window.innerHeight - 210,
        total: 0,
        pageSize: 10,
        currentPage: 1,
        roleName: '',
        remark: ''
      },
      tableData: [],
      //弹框属性
      dialog: {
        title: '',
        visible: false,
        width: 800,
        height: 200,
      },
    }
  },
  methods: {
    //分配权限弹框关闭
    assignClose() {
      this.assignDialog.visible = false
    },
    //分配权限弹框确定
    async assignConfirm() {
      console.log(this.$refs.assignTree.getCheckedKeys())
      console.log(this.$refs.assignTree.getHalfCheckedKeys())

      let ids=this.$refs.assignTree.getCheckedKeys().concat(this.$refs.assignTree.getHalfCheckedKeys())
      let param={
        roleId:this.roleId,
        list:ids
      }
      let res=await saveAssignRoleApi(param)

      if (res && res.code==200){
        this.$message.success(res.msg)
        this.assignDialog.visible = false
      }
    },
    //分配权限
    async assignBtn(row) {
      //清空数据
      this.roleId=''
      this.assignTreeData=[]
      this.assignTreeChecked=[]

      console.log(row)
      //设置弹框属性
      this.assignDialog.title = '给->  ' + row.roleName + '  <-分配权限'
      this.roleId = row.roleId
      this.assignDialog.visible = true
      //获取权限树
      let param = {
        roleId: row.roleId,
        userId: getUserId()
      }
      let res = await getAssignRoleApi(param)
      if (res && res.code == 200) {
        console.log(res)
        //树的数据
        this.assignTreeData = res.data.menuList
        //回显的数据
        this.assignTreeChecked = res.data.checkList

        //获取回显的数据
        if (this.assignTreeChecked.length > 0) {
          let newArr = []
          this.assignTreeChecked.forEach(item => {
            this.checked(item, this.assignTreeData, newArr)
          })
          //设置选中的节点
          this.assignTreeChecked = newArr
        }
      }
    },
    //查询回显数据
    checked(id, data, newArr) {
      data.forEach(item => {
        if (item.menuId == id) {
          //判断是否是最后一个节点
          if (item.children && item.children.length == 0) {
            newArr.push(item.menuId)
          }
        } else {
          if (item.children && item.children.length != 0) {
            //递归调用，
            this.checked(id, item.children, newArr)
          }
        }
      })
    },
    addBtn(row) {
      this.dialog.title = "新增角色"
      this.dialog.visible = true
      //清空表单
      this.$resetForm('addRef', this.addModel)
      this.addModel.type = '0'
    },
    //删除
    async deleteBtn(row) {
      let confirm = await this.$myconfirm("确定删除该角色吗？")
      if (confirm) {
        let result = await deleteRoleApi({roleId: row.roleId})
        if (result && result.code == 200) {
          //刷新表格
          this.getList()
          //信息提示
          this.$message({type: 'success', message: result.msg})
        }
      }
    },
    editBtn(row) {
      this.dialog.title = "编辑用户"
      this.dialog.visible = true
      //清空表单
      this.$resetForm('addRef', this.addModel)
      this.dialog.type = '1'
      this.$objCopy(row, this.addModel)
    },
    //弹框取消
    onClose() {
      this.dialog.visible = false;
    },
    //弹框确定
    onConfirm() {
      this.$refs.addRef.validate(async (valid) => {
        if (valid) {
          let res = null
          if (this.addModel.type == '0') {
            res = await addRoleApi(this.addModel)
          } else {
            res = await editRoleApi(this.addModel);
          }
          if (res && res.code == 200) {
            //信息提示
            this.$message({type: 'success', message: res.msg})
            //刷新表格
            this.getList()
            this.dialog.visible = false;
          }
        }
      })

    },
    searchBtn() {
      this.getList();
    },
    resetBtn() {
      this.listParam.roleName = ''
      this.getList()
    },
    sizeChange(val) {
    },
    currentChange(val) {
    },

    //获取表格数据
    async getList() {
      let res = await getListApi(this.listParam);
      if (res && res.code == 200) {
        this.tableData = res.data.records
        this.total = res.data.total
        console.log(res)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {

    })
  },
  created() {
    this.getList()
  }
}
</script>

<style lang="scss" scoped>

</style>
